<template>
	<div style="width: 100%;padding-top:10px">
		<div v-if="tableData.length==0" style="width: 100%;padding: 10px;">
			<el-button @click="addLinkDialog = true" size="small" type="primary" plain style="width: 100%;">新建连接</el-button>
		</div>
		<el-table v-else :data="tableData" style="width: 100%" row-key="id" 
			:show-header="false" lazy :highlight-current-row="true" :load="load" @cell-click="cellClick" @cell-mouse-leave="cellMouseLeave">
			<el-table-column prop="name" label="名称" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<i class="el-icon-link" style="margin-right: 8px;" v-if="scope.row.type =='link'"></i>
					<i class="el-icon-coin" style="margin-right: 8px;" v-if="scope.row.type =='db'"></i>
					<i class="el-icon-document-copy" style="margin-right: 8px;" v-if="scope.row.type =='stable'"></i>
					<i class="el-icon-tickets" style="margin-right: 8px;" v-if="scope.row.type =='table'"></i>
					{{scope.row.name}}
				</template>
			</el-table-column>
			<el-table-column prop="opt" label="操作" width="90">
				<template slot-scope="scope">
					<el-tooltip class="item" effect="dark" content="删除连接" placement="top-start">
						<el-button type="text" size="mini" icon="el-icon-delete" v-if="scope.row.type=='link'" @click="delLink(scope.row)"></el-button>
					</el-tooltip>
					<el-tooltip class="item" effect="dark" content="重新加载连接" placement="top-start">
						<el-button type="text" size="mini" icon="el-icon-refresh" v-if="scope.row.type=='link'" @click="reload(scope.row)"></el-button>
					</el-tooltip>
					<el-tooltip class="item" effect="dark" content="创建数据库" placement="top-start">
						<el-button type="text" size="mini" icon="el-icon-plus" v-if="scope.row.type=='link'" @click="showDBDialog(scope.row)"></el-button>
					</el-tooltip>
					
					<el-tooltip class="item" effect="dark" content="删除数据库" placement="top-start">
						<el-button type="text" size="mini" icon="el-icon-delete" v-if="scope.row.type=='db' && scope.row.cellMouse" @click="delDb(scope.row)"></el-button>
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog :close-on-click-modal="false" :before-close="cancelAddLink" :visible.sync="addLinkDialog" title="新建连接">
		  <el-form :model="linkForm"  ref="linkForm" :rules="linkFormRules" label-width="80px">
			<el-form-item label="名称" prop="name">
				<el-input v-model="linkForm.name"></el-input>
			</el-form-item>
			<el-form-item label="主机地址" prop="host">
				<el-input v-model="linkForm.host"></el-input>
			</el-form-item>
			<el-form-item label="端口" prop="port">
				<el-input v-model="linkForm.port"></el-input>
			</el-form-item>
			<el-form-item label="用户名" prop="user">
				<el-input v-model="linkForm.user"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input type="password" v-model="linkForm.password"></el-input>
			</el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
			<el-button @click="cancelAddLink" size="medium">取 消</el-button>
			<el-button type="primary" @click="confirmAddLink" size="medium">确 定</el-button>
		  </div>
		</el-dialog>
		
		<!-- 添加数据库的弹窗 -->
		<el-dialog :close-on-click-modal="false" :before-close="cancelAddDB" :visible.sync="addDBDialog" title="添加数据库" width="600px">
		  <el-form :model="dbForm"  ref="dbForm" :rules="dbFormRules" label-width="90px">
		    <el-form-item label="名称" prop="name">
		      <el-input v-model="dbForm.name" maxlength="33"></el-input>
		    </el-form-item>
			<el-col :span="12">
				<el-form-item label="压缩度" prop="comp">
				  <el-select v-model="dbForm.comp" placeholder="文件压缩度">
					<el-option label="0" value="0"></el-option>
					<el-option label="1" value="1"></el-option>
					<el-option label="2" value="2"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="副本数" prop="relica">
				  <el-select v-model="dbForm.replica" placeholder="数据库副本数">
				    <el-option label="1" value="1"></el-option>
				    <el-option label="2" value="2"></el-option>
				    <el-option label="3" value="3"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="保存天数" prop="keep">
				  <el-input-number v-model="dbForm.keep" :min="3650":max="365000" style="width: 100%;"></el-input-number>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="开启更新" prop="update">
				  <el-select v-model="dbForm.update" placeholder="是否开启更新">
				    <el-option label="关闭" value="0"></el-option>
				    <el-option label="开启" value="1"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="quorum" prop="quorum">
				  <el-select v-model="dbForm.quorum" placeholder="写入确认数">
				    <el-option label="1" value="1"></el-option>
				    <el-option label="2" value="2"></el-option>
				    <el-option label="3" value="3"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="blocks" prop="blocks">
				    <el-input-number v-model="dbForm.blocks" :min="3"	:max="1000"  style="width: 100%;"></el-input-number>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="cachelast" prop="cachelast">
				  <el-select v-model="dbForm.cachelast" placeholder="缓存设置">
				    <el-option label="不缓存" value="0"></el-option>
					<el-option label="最近一行" value="1"></el-option>
				    <el-option label="最近的非 NULL 值" value="2"></el-option>
				    <el-option label="同时打开缓存最近行和列" value="3"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item label="wal" prop="wal">
				  <el-select v-model="dbForm.wal" placeholder="落盘方式">
					<el-option label="写WAL不执行fsync" value="1"></el-option>
				    <el-option label="写WAL执行fsync" value="2"></el-option>
				  </el-select>
				</el-form-item>
			</el-col>
			<!-- <el-col :span="12"> -->
				<el-form-item label="fsync" prop="fsync">
					<el-input-number v-model="dbForm.fsync" :min="0"	:max="180000"  style="width: 100%;"></el-input-number>
				</el-form-item>
			<!-- </el-col> -->
			</el-form>
		    <div slot="footer" class="dialog-footer">
				<el-button @click="addDBDialog = false" size="medium">取 消</el-button>
				<el-button type="primary" @click="postaddDB" size="medium">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {mapGetters} from 'vuex'
	import * as taos from '../api/taosrestful.js'
	import bus from '../utils/bus'

	export default {
		name: "dbNav",
		data() {
			return {
				tableData: [],
				linkForm: {'name':'','host':'','port':'6041','user':'','password':''},
				linkFormRules:{
					name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
					host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
					port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
					user: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
					password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
				},
				addLinkDialog: false,
				addDBDialog: false,
				dbForm:{'name':'','comp':'2','replica':'1','keep':3650,'update':'0','quorum':'1','blocks':'4','cachelast':0,'wal':1,'fsync':3000},
				dbFormRules:{
					name:[{required: true, message: '请输入名称', trigger: 'blur'}],
					comp:[{required: true, message: '请输入压缩度', trigger: 'blur'}],
					replica:[{required: true, message: '请输入副本数', trigger: 'blur'}],
					keep:[{required: true, message: '请输入保存天数', trigger: 'blur'}],
					update:[{required: true, message: '请选择是否更新', trigger: 'blur'}],
					quorum:[{required: true, message: '请输入quorum', trigger: 'blur'}],
					blocks:[{required: true, message: '请输入数据块数量', trigger: 'blur'}],
					cachelast:[{required: true, message: '请选择缓存方式', trigger: 'blur'}],
					wal:[{required: true, message: '请选择落盘方式', trigger: 'blur'}],
					fsync:[{required: true, message: '请输入fsync执行', trigger: 'blur'}]
				},
				curLink:{},
				cellMouse: false
			}
		},
		computed: {
			...mapGetters(['link'])
		},
		created() {
			this.init()
		},
		methods: {
			init(){
				this.tableData = []
				if(this.link.name){
					this.tableData.push(this.link)
				}
			},
			//加载
			load(tree, treeNode, resolve) {
				if (tree.type === 'link') {
					let tmpPayload = {ip: tree.host,port: tree.port,user: tree.user,password: tree.password}
					taos.showDatabases(tmpPayload).then(data => {
						if (data.res) {
							let treeNodes = []
							data.data.forEach(function(db) {
								let dbName = db.name?db.name:db[0]
								let dbInfo = {}
								dbInfo.hasChildren = true
								dbInfo.id = tree.id+dbName
								dbInfo.linkId = tree.id
								dbInfo.type = 'db'
								dbInfo.name = dbName
								treeNodes.push(dbInfo)
							})
							resolve(treeNodes)
						} else {
							this.$message({message: '连接失败',type: 'error',duration: 1000})
						}
					})
				} else if (tree.type === 'db') {
					let treeNodes = []
					treeNodes.push({"id": tree.id +"_"+tree.name+"_stable","name": "stable","type": "stable","dbName":tree.name,"linkId":tree.linkId})
					treeNodes.push({"id": tree.id +"_"+tree.name+"_table","name": "table","type": "table","dbName":tree.name,"linkId":tree.linkId})
					resolve(treeNodes)
				}
			},
			//点击
			cellClick(row, column, cell, event){
				if(column.property =='opt'){//第二列的按扭
				}else{
					if(row.type==='db'){//显示数据库删除按扭
						row.cellMouse = true
					}
					let link = this.link
					this.$store.dispatch("changeCurObject", {"type":row.type,"link":row.type==='link'?row:link,"dbName":row.type==='db'?row.name:row.dbName})
					.then(() => {
						bus.$emit('changeCurObject_'+row.type,'切换');
						bus.$emit('nav')
					}).catch((e) => {console.error(e)})
				}
			},
			//重新加载
			reload(row){
				this.tableData = []
				let that = this
				this.$nextTick(() => {
					that.tableData.push(row)
				})
			},
			delLink(row){
				this.$confirm('请确定是否删除连接【' + row.name + '】', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					localStorage.clear()
					this.tableData = []
					this.$store.dispatch("addDbLink", {})
					.then(() => {
						this.$message({message: '连接删除成功',type: 'success',duration: 1000})
					}).catch((e) => {console.error(e)})
				}).catch(function(error) {
					console.log(error)
				})
			},
			cancelAddLink(){
				this.addLinkDialog = false
			},
			confirmAddLink(){
				this.$refs['linkForm'].validate((valid) => {
					if (valid) {
						localStorage.clear()
						this.linkForm.id=new Date().getTime()
						this.linkForm.hasChildren=true
						this.linkForm.type='link'
						this.tableData.push(this.linkForm)
						this.$store.dispatch("addDbLink", this.linkForm)
						.then(() => {
						  this.addLinkDialog = false
						  this.linkForm={}
						})
						.catch((e) => {console.error(e)})
					}
				})
			},
			//数据库
			showDBDialog(row){
				this.addDBDialog = true
				this.curLink = row
			},
			cancelAddDB(){
				this.addDBDialog = false
			},
			postaddDB(){
				this.$refs['dbForm'].validate((valid) => {
					if (valid) {
						if(this.dbForm.replica < this.dbForm.quorum){
							this.$message({message: 'replica应大于等于quorum',type: 'error',duration:1000})
							return 
						}
						let payload = {ip: this.curLink.host,port: this.curLink.port,user: this.curLink.user,password: this.curLink.password}
						taos.createDatabase(this.dbForm, payload).then(data => {
							if(data.res){
								this.$message({message: '添加成功',type: 'success',duration:1000})
								this.reload(this.curLink)
								this.addDBDialog = false
							}else{
								this.$message({message: data.msg,type: 'error',duration:1000})
							}
						})
					}
				})
			},
			cellMouseLeave(row, column, cell, event){
				if(row.type==='db'){
					row.cellMouse = false
				}
			},
			//删除数据库
			delDb(row){
				this.$confirm('请确定是否删除数据库【' + row.name + '】', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let link = this.link
					let payload = {ip: link.host,port: link.port,user: link.user,password: link.password}
					taos.dropDatabase(row.name, payload).then((response) => {
						this.$message({type: 'success',message: '操作成功!'})
						this.reload(link)
					})
				}).catch(function(error) {
					console.log(error)
				})
			}
		}
	}
</script>